import React, { useEffect, useState } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { useNavigate } from 'react-router-dom';
import {
  Table,
  Button,
  Space,
  Popconfirm,
  message,
  Tag,
  Input,
  Select,
  Card,
  Row,
  Col,
  Statistic,
  DatePicker,
  Spin,
  Tooltip,
  Modal
} from 'antd';
import {
  EyeOutlined,
  SearchOutlined,
  CalendarOutlined,
  CloseCircleOutlined,
  CheckCircleOutlined
} from '@ant-design/icons';
import {
  fetchBookings,
  cancelBooking,
  fetchPassengerBookings,
  searchBookings
} from '../../store/slices/bookingSlice';

const { Search } = Input;
const { Option } = Select;
const { RangePicker } = DatePicker;

const BookingList = ({ passengerId }) => {
  const [searchText, setSearchText] = useState('');
  const [selectedStatus, setSelectedStatus] = useState('all');
  const [dateRange, setDateRange] = useState([]);
  const [loading, setLoading] = useState(false);
  const [cancelModal, setCancelModal] = useState({
    visible: false,
    booking: null
  });
  
  const dispatch = useDispatch();
  const navigate = useNavigate();
  const { bookings, loading: listLoading, pagination } = useSelector(state => state.bookings);

  useEffect(() => {
    loadBookings();
  }, [dispatch, passengerId]);

  const loadBookings = async (params = {}) => {
    setLoading(true);
    try {
      if (passengerId) {
        await dispatch(fetchPassengerBookings(passengerId)).unwrap();
      } else {
        await dispatch(fetchBookings({
          page: 1,
          limit: 10,
          ...params
        })).unwrap();
      }
    } catch (error) {
      message.error('加载预订列表失败');
    } finally {
      setLoading(false);
    }
  };

  const handleSearch = async () => {
    setLoading(true);
    try {
      // 根据搜索文本判断是预订号、乘客姓名还是航班号
      let searchParams = {};
      if (searchText) {
        // 简单判断：如果是字母+数字格式，可能是航班号
        if (/^[A-Z0-9]{2,}$/i.test(searchText)) {
          searchParams.flight_number = searchText;
        } else if (/^[A-Z0-9]{6,}$/i.test(searchText)) {
          // 如果是6位以上字母数字，可能是预订号
          searchParams.booking_number = searchText;
        } else {
          // 否则认为是乘客姓名
          searchParams.passenger_name = searchText;
        }
      }
      
      await dispatch(searchBookings(searchParams)).unwrap();
    } catch (error) {
      message.error('搜索预订失败');
    } finally {
      setLoading(false);
    }
  };

  const handleReset = () => {
    setSearchText('');
    setSelectedStatus('all');
    setDateRange([]);
    loadBookings();
  };

  const showCancelModal = (booking) => {
    setCancelModal({ visible: true, booking });
  };

  const handleCancel = async () => {
    try {
      await dispatch(cancelBooking(cancelModal.booking.booking_number)).unwrap();
      message.success('预订取消成功');
      setCancelModal({ visible: false, booking: null });
      loadBookings();
    } catch (error) {
      message.error('取消预订失败');
    }
  };

  const getStatusColor = (status) => {
    const colors = {
      'confirmed': 'green',
      'pending': 'orange',
      'cancelled': 'red',
      'completed': 'blue'
    };
    return colors[status] || 'default';
  };

  const getStatusText = (status) => {
    const texts = {
      'confirmed': '已确认',
      'pending': '待确认',
      'cancelled': '已取消',
      'completed': '已完成'
    };
    return texts[status] || status;
  };

  const columns = [
    {
      title: '预订号',
      dataIndex: 'booking_number',
      key: 'booking_number',
      render: (text) => (
        <Button type="link" onClick={() => navigate(`/bookings/${text}`)}>
          {text}
        </Button>
      )
    },
    {
      title: '航班号',
      dataIndex: 'flight_id',
      key: 'flight_id',
      render: (flightId) => `航班${flightId}`
    },
    {
      title: '乘客',
      dataIndex: 'passenger_id',
      key: 'passenger_id',
      render: (passengerId) => `乘客${passengerId}`
    },
    {
      title: '出发地',
      dataIndex: 'departure_airport',
      key: 'departure_airport',
      render: () => '-'
    },
    {
      title: '目的地',
      dataIndex: 'arrival_airport',
      key: 'arrival_airport',
      render: () => '-'
    },
    {
      title: '起飞时间',
      dataIndex: 'departure_time',
      key: 'departure_time',
      render: () => '-'
    },
    {
      title: '状态',
      dataIndex: 'booking_status',
      key: 'booking_status',
      render: (status) => (
        <Tag color={getStatusColor(status)}>
          {getStatusText(status)}
        </Tag>
      )
    },
    {
      title: '价格',
      dataIndex: 'price',
      key: 'price',
      render: (price) => `¥${price || 0}`,
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space size="middle">
          <Button
            type="text"
            icon={<EyeOutlined />}
            onClick={() => navigate(`/bookings/${record.booking_number}`)}
          >
            查看
          </Button>
          {record.booking_status === 'confirmed' && (
            <Button
              type="text"
              danger
              icon={<CloseCircleOutlined />}
              onClick={() => showCancelModal(record)}
            >
              取消
            </Button>
          )}
        </Space>
      ),
    },
  ];

  const stats = React.useMemo(() => {
    if (!bookings) return { total: 0, confirmed: 0, cancelled: 0, pending: 0 };
    
    return {
      total: bookings.length,
      confirmed: bookings.filter(b => b.booking_status === 'confirmed').length,
      cancelled: bookings.filter(b => b.booking_status === 'cancelled').length,
      pending: bookings.filter(b => b.booking_status === 'pending').length,
    };
  }, [bookings]);

  return (
    <div style={{ padding: 24 }}>
      <Card title={passengerId ? '我的预订' : '预订管理'}>
        <Row gutter={16} style={{ marginBottom: 16 }}>
          <Col span={6}>
            <Card>
              <Statistic
                title="总预订数"
                value={stats.total}
                prefix={<CalendarOutlined />}
              />
            </Card>
          </Col>
          <Col span={6}>
            <Card>
              <Statistic
                title="已确认"
                value={stats.confirmed}
                valueStyle={{ color: '#3f8600' }}
                prefix={<CheckCircleOutlined />}
              />
            </Card>
          </Col>
          <Col span={6}>
            <Card>
              <Statistic
                title="已取消"
                value={stats.cancelled}
                valueStyle={{ color: '#cf1322' }}
                prefix={<CloseCircleOutlined />}
              />
            </Card>
          </Col>
          <Col span={6}>
            <Card>
              <Statistic
                title="待确认"
                value={stats.pending}
                valueStyle={{ color: '#faad14' }}
                prefix={<CalendarOutlined />}
              />
            </Card>
          </Col>
        </Row>

        <Row gutter={16} style={{ marginBottom: 16 }}>
          <Col span={8}>
            <Search
              placeholder="搜索预订号或乘客"
              prefix={<SearchOutlined />}
              value={searchText}
              onChange={(e) => setSearchText(e.target.value)}
              onSearch={handleSearch}
              style={{ width: '100%' }}
            />
          </Col>
          <Col span={4}>
            <Select
              placeholder="选择状态"
              style={{ width: '100%' }}
              value={selectedStatus}
              onChange={setSelectedStatus}
            >
              <Option value="all">全部状态</Option>
              <Option value="confirmed">已确认</Option>
              <Option value="pending">待确认</Option>
              <Option value="cancelled">已取消</Option>
              <Option value="completed">已完成</Option>
            </Select>
          </Col>
          <Col span={6}>
            <RangePicker
              style={{ width: '100%' }}
              value={dateRange}
              onChange={setDateRange}
            />
          </Col>
          <Col span={6}>
            <Space>
              <Button type="primary" onClick={handleSearch}>
                搜索
              </Button>
              <Button onClick={handleReset}>
                重置
              </Button>
            </Space>
          </Col>
        </Row>

        <Table
          columns={columns}
          dataSource={bookings}
          rowKey="booking_number"
          loading={loading || listLoading}
          pagination={{
            total: pagination.total,
            pageSize: pagination.pageSize,
            current: pagination.current,
            onChange: (page, pageSize) => {
              loadBookings({ page, limit: pageSize });
            },
          }}
        />
      </Card>

      <Modal
        title="取消预订"
        open={cancelModal.visible}
        onOk={handleCancel}
        onCancel={() => setCancelModal({ visible: false, booking: null })}
        okText="确认取消"
        cancelText="返回"
        okButtonProps={{ danger: true }}
      >
        <p>确定要取消预订 {cancelModal.booking?.booking_number} 吗？</p>
        <p>此操作不可撤销。</p>
      </Modal>
    </div>
  );
};

export default BookingList;